'use client'

import * as fabric from 'fabric'
import { useEffect, useState } from 'react'

export default function Page() {
  // 画布实例
  let canvas: fabric.Canvas | null = null
  // 画布的宽度
  const [canvasWidth, setCanvasWidth] = useState(400)
  // 画布的高度
  const [canvasHeight, setCanvasHeight] = useState(400)
  /**
   * 初始化画布
   */
  const onInitCanvas = () => {
    canvas = new fabric.Canvas('drawCanvas')

    canvas.on('mouse:wheel', function (e) {
      e.e.preventDefault() // 阻止默认滚动行为

      // 获取滚轮事件的详细信息
      const delta = e.e.deltaY || 0

      // 获取当前缩放级别
      const currentZoom = canvas!.getZoom()

      console.log(currentZoom)

      // 缩放步长
      const zoomStep = 0.1

      // 判断滚轮方向并执行缩放
      if (delta > 0) {
        // 向下滚动 - 缩小画布
        const newZoom = Math.max(0.1, currentZoom - zoomStep)
        canvas!.setZoom(newZoom)
        console.log('画布缩小，当前缩放级别:', newZoom)
      } else if (delta < 0) {
        // 向上滚动 - 放大画布
        const newZoom = Math.min(5, currentZoom + zoomStep)
        canvas!.setZoom(newZoom)
        console.log('画布放大，当前缩放级别:', newZoom)
      }

      // 重新渲染画布
      canvas!.renderAll()
    })

    // 添加矩形
    const rect = new fabric.Rect({
      width: 100,
      height: 100,
      fill: 'red'
    })

    canvas.add(rect)
  }

  useEffect(() => {
    onInitCanvas()
  }, [])

  return (
    <div>
      <canvas
        id="drawCanvas"
        width={canvasWidth}
        height={canvasHeight}
        className="border border-amber-600"
      ></canvas>
    </div>
  )
}
